package com.example.myapplication;

import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;

import com.example.myapplication.base.BaseActivity;
import com.example.myapplication.dialogs.PrivacyDailog;
import com.example.myapplication.dialogs.ShowUserDailog;
import com.example.myapplication.utils.LogUtils;

import org.json.JSONException;
import org.json.JSONObject;

/***
 * 用户须知的Activity
 */
public class UserActivity extends BaseActivity implements View.OnClickListener {

    private TextView tv_agree, tv_noagree, tv_privacy;
    private WebView webView;
    private int buyType = 0;//支付类型，0：按期付款，1全款
    private int assure = 0;//是否走担保人，0：非担保人，1担保人
    private boolean isError = false;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user);
        try{
            initView();
            initWebView();
            initData();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        String hUrl = "http://mtest.molichuxing.com/contract-moli/user.html";
        LogUtils.i("dove", "load-url-" + hUrl);
        webView.loadUrl(hUrl);
//        switch (assure) {
//            case 0:
//                webView.loadUrl(UrlManager.User_Read);
//                break;
//            case 1:
//                webView.loadUrl(UrlManager.Rent_Read);
//                break;
//        }
    }

    /**
     * 初始化View
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        webView = findViewById(R.id.tv_webview);
        tv_agree = findViewById(R.id.tv_agree);
        tv_noagree = findViewById(R.id.tv_noagree);
        tv_privacy = findViewById(R.id.tv_privacy);
        webView.getSettings().setBuiltInZoomControls(false);
        tv_privacy.setOnClickListener(this);
        tv_agree.setOnClickListener(this);
        tv_noagree.setOnClickListener(this);
    }

    /***
     *  点击事件
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //点击同意
            case R.id.tv_agree:
                ShowUserDailog.showDailog(mContext, mActivity, buyType, assure);
                break;
            //点击隐藏政策
            case R.id.tv_privacy:
                PrivacyDailog.showDailog(mContext, mActivity);
                break;
        }
    }


    /**
     * 初始化WebView
     */
    private void initWebView() {
        setWebView(webView);
        setWebViewMonitor(webView);
        registerHandler();
    }

    /**
     * 注册接口
     */
    private void registerHandler() {
        webView.addJavascriptInterface(new JsInterfaces(), "obj");
    }

    /**
     * 添加webview监听
     *
     * @param mWebView
     */
    private void setWebViewMonitor(final WebView mWebView) {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                setShowProgress(true);
                LogUtils.i("dove", "开始请求" + url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                setShowProgress(false);
                LogUtils.i("dove", "当前请求" + url);
                if (!isError) {
                    Log.i("dove","1网页加载成功");
                    //回调成功后的相关操作
                } else {
                    Log.i("dove","1网页加载失败");
                    Toast.makeText(mContext,"1网页加载失败",Toast.LENGTH_LONG).show();
                }
                isError = false;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log.i("dove","error--"+error);
                isError = true;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                LogUtils.i("dove", "url-" + url);
                view.loadUrl(url);
                return true;
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                LogUtils.i("dove", "当前加载进度" + newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                Log.i("dove","title--"+title);
                if(title.contains("404")||title.contains("500")
                        ||title.contains("error")){
                    Log.i("dove","3网页加载失败");
                    Toast.makeText(mContext,"3网页加载失败",Toast.LENGTH_LONG).show();
                }else{
                    Log.i("dove","3网页加载成功");
                }
            }
        });
    }

    /**
     * webview常规设置
     */
    private void setWebView(WebView mWebView) {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);//设置能够解析Javascript
        webSettings.setDomStorageEnabled(true);//设置适应Html5 //重点是这个设置
        //设置字符编码
        webSettings.setDefaultTextEncodingName("utf-8");
        // 支持缩放
        webSettings.setSupportZoom(false);
        // //启用内置缩放装置
        webSettings.setBuiltInZoomControls(false);
        // 支持自动加载图片
        webSettings.setLoadsImagesAutomatically(true);
        // 支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //设置缓存
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //清空所有Cookie
        CookieSyncManager.createInstance(mContext.getApplicationContext());  //Create a singleton CookieSyncManager within a context
        CookieManager cookieManager = CookieManager.getInstance(); // the singleton CookieManager instance
        cookieManager.removeAllCookie();// Removes all cookies.
        CookieSyncManager.getInstance().sync(); // forces sync manager to sync now

        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.getSettings().setJavaScriptEnabled(false);
        webView.clearCache(true);

        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        mContext.deleteDatabase("WebView.db");
        mContext.deleteDatabase("WebViewCache.db");
        webView.clearCache(true);
        webView.clearFormData();
        mContext.getCacheDir().delete();
    }

    private class JsInterfaces {
        @JavascriptInterface
        public void getUserInfo(String json) {
            LogUtils.i("", "获取用户信息");
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("name", "hello world");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    public void sendUserInfo(JSONObject jsonObject) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("funJsInfo(" + jsonObject + ")", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    LogUtils.i("dove", "返回用户信息成功");
                }
            });
        } else {
            webView.loadUrl("javascript:funJsInfo(" + jsonObject + ")");
        }
    }
}
